import os
import sys
import json
import argparse

def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument("--path", type=str, required=True)
    parser.add_argument("--line", nargs="+", type=int)
    return parser.parse_args()

def naive_join_tokens(tokens):
    string = ""
    for token in tokens:
        if token[:2] == "##":
            string += token[2:]
        elif string == "":
            string += token
        else:
            string += " " + token
    return string

def analyze(relation):
    relation = json.loads(relation.strip())
    candidates = relation["candidates"]
    relations = relation["relations"]
    context = relation["context"]
    candidates = [ naive_join_tokens(context[x[0]:x[1]+1]) for x in candidates ]
    relations = [ (candidates[x[0]], candidates[x[1]]) for x in relations ]
    print(naive_join_tokens(context))
    for a, b in relations:
        print("{} -> {}".format(a, b))


def main():
    args = parse_args()
    file_name = args.path
    line_indices = args.line
    with open(file_name, "r") as f:
        relations = f.readlines()
        if line_indices != None:
            for line_index in line_indices:
                if 0 <= line_index and line_index < len(relations):
                    print(f"============{line_index}============")
                    relation = relations[line_index]
                    analyze(relation)
        else:
            for line_index, relation in enumerate(relations):
                print(f"============{line_index}============")
                analyze(relation)

if __name__=="__main__":
    main()